import random
import re
from rest_framework.generics import CreateAPIView, GenericAPIView, RetrieveAPIView
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from . import serializers
from . import constants
from apps.utils import cloopen
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from .utils import OpenidUtils
from rest_framework_jwt.settings import api_settings
from django.http import JsonResponse
from carts.utils import merge_cart_cookie_to_redis
from django.contrib.auth import get_user_model

User = get_user_model()


class UserNotLogin(APIView):
    serializers = serializers.CreateUserSerializer

    def post(self, request):
        params = request.data
        # 实例化对象,调用get_openid获取用户唯一标识openid
        oauth = OpenidUtils(params.get('code'))
        userName = oauth.get_openid()
        try:
            user = User.objects.get(username=userName)
        except Exception as e:
            user = None
        if user:
            pass
        else:
            # 未登录用户创建新用户
            user = User.objects.create_user(
                username=userName,
                password=oauth.random_str(10),
                nickname='',
                gender=1,
                country='',
                province='',
                city='',
                img_url='')
            user.save()

        ret = {'code': '00000', 'msg': None, 'data': {}}

        ret['msg'] = '授权成功'
        ret['data'] = {
            'user_id': user.id,
        }
        return JsonResponse(ret)


class UserLogin(APIView):
    serializers = serializers.CreateUserSerializer

    def post(self, request):
        params = request.data
        # 实例化对象,调用get_openid获取用户唯一标识openid
        oauth = OpenidUtils(params.get('code'))
        userName = oauth.get_openid()
        userInfo = params.get('userinfo')
        try:
            user = User.objects.get(username=userName)
        except Exception as e:
            user = None
        if user:
            # 更新用户信息
            user = User.objects.get(username=userName)
            user.nickname = userInfo.get('nickname')
            user.gender = userInfo.get('gender')
            user.country = userInfo.get('country')
            user.province = userInfo.get('province')
            user.city = userInfo.get('city')
            user.img_url = userInfo.get('image_url')
            user.save()
        else:
            # 注册新用户
            user = User.objects.create_user(
                username=userName,
                password=oauth.random_str(10),
                nickname=userInfo.get('nickname'),
                gender=userInfo.get('gender'),
                country=userInfo.get('country'),
                province=userInfo.get('province'),
                city=userInfo.get('city'),
                img_url=userInfo.get('image_url'))
            user.save()
        # 手动生成JWT
        # 手动生成token验证
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        ret = {'code': '00000', 'msg': None, 'data': {}}

        ret['msg'] = '授权成功'
        ret['data'] = {
            'token': token,
            'user_id': user.id,
            'nickname': user.nickname
        }
        # return JsonResponse(ret)
        response = JsonResponse(ret)
        response = merge_cart_cookie_to_redis(request, response, user)
        return response


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer

    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """
        GET 方法请求用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.filter(is_deleted=0).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)
        if count == 0:
            ret = super().create(request, *args, **kwargs)
            request.user.default_address_id = ret.data.get('id')
            request.user.save()
            return ret
        ret = super().create(request, *args, **kwargs)
        is_default = request.data.get('is_default')
        if is_default:
            request.user.default_address_id = ret.data.get('id')
            request.user.save()
            return ret
        else:
            return ret

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        # address.is_deleted = True
        # address.save()
        # 进行逻辑删除
        address.is_deleted = True
        address.save()
        user = self.request.user
        try:
            user = User.objects.get(id=user.id)
            user.default_address_id = None
            user.save()
            return Response({'ResultCode': 1, 'message': '删除成功'})
        except User.DoesNotExist:
            return Response({'ResultCode': 0, 'message': '用户不存在，删除失败'})

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        # 当设置默认地址的时候更新收货地址
        serializer = self.get_serializer(address, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 设置默认地址
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


# 用户个人中心
class UserInfoView(APIView):
    """
    展示用户个人信息
    """
    serializer_class = serializers.UserInfoSerializer

    def get(self, request):
        user_id = self.request.query_params.get('user_id')
        user = User.objects.get(id=user_id)
        if user.gender_userinfo is None:
            gender = user.gender
        else:
            gender = user.gender_userinfo
        # 返回加密的手机号码
        if user.mobile:
            mobile = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', user.mobile)
            return Response({
                'realname': user.realname,
                'gender': gender,
                'mobile': mobile,
                'image_url': str(user.img_url),
            })
        else:
            return Response({
                'realname': user.realname,
                'gender': gender,
                'mobile': user.mobile,
                'image_url': str(user.img_url),
            })


# 用户修改真实姓名
class UserRealNameView(APIView):
    """
    用户修改个人姓名
    """
    serializer_class = serializers.UserRealNameSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        realname = request.data.get('realname')
        user_id = request.data.get('id')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({'Resultcode': 0, 'message': '用户不存在'})
        user.realname = realname
        user.save()
        return Response({
            'Resultcode': 1,
            'message': '修改成功',
            'realname': realname,
        }, status=status.HTTP_201_CREATED)


# 用户修改性别
class UserGenderView(APIView):
    """
    用户修改性别
    """
    serializer_class = serializers.UserGenderSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        gender_userinfo = request.data.get('gender_userinfo')
        user_id = request.data.get('id')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({'Resultcode': 0, 'message': '用户不存在'})
        user.gender_userinfo = gender_userinfo
        user.save()
        return Response({'Resultcode': 1, 'message': '修改成功', 'gender_userinfo': gender_userinfo})


# 修改手机号码的时候发送短信验证码
class SMSCodeView(GenericAPIView):
    """
    修改手机号码的时候发送短信验证码
    """
    serializer_class = serializers.UserMobileSendSMSCodeSerializer

    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存验证码以及发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_REDIS_EXPIRES, 1)
        # 让管道执行命令
        pl.execute()

        # 发送短信验证码
        # cloopen(mobile,sms_code)

        return Response({'Resultcode': 1, 'message': '发送成功'})


# 用户注册手机号码
class UserMobileRegisterView(APIView):
    serializer_class = serializers.UserMobileRegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        mobile = request.data.get('mobile')
        user_id = request.data.get('id')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({'Resultcode': 0, 'message': '用户不存在'})
        user.mobile = mobile
        user.save()
        # 返回加密号码
        ret_mobile = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', user.mobile)
        return Response({
            'Resultcode': 1,
            'message': '添加成功',
            'mobile': ret_mobile,
        }, status=status.HTTP_201_CREATED)


# 意见反馈
# class FeedBackView(mixins.CreateModelMixin,GenericAPIView):
class FeedBackView(CreateAPIView):
    serializer_class = serializers.FeedBackSerializer

    # permission_classes = (IsAuthenticated,)

    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return Response({'ResultCode': 1, 'Message': '提交成功'}, status=status.HTTP_201_CREATED)
